<?php

$db = new SQLiteDatabase('InstantInput.db');

if ($_GET['action'] == "get_metrics")
{	
	$result = $db->query("SELECT * FROM Metrics WHERE class_id = " . $_GET['uniqueCourseNumber'] . " ORDER BY metric_id DESC");
	
	$clarity_sum = 0;
	$pacing_sum = 0;
	
	$num_clarity = 0;
	$num_pacing = 0;
	
	$students_clarity = array();
	$students_pacing = array();
	
	while ($result->valid()) 
	{
		$curr = $result->current();
		
		if ($curr['metric_type'] == "clarity")
		{
			if(!in_array($curr['sunet_id'], $students_clarity))
			{
				$students_clarity[] = $curr['sunet_id'];
				$num_clarity = $num_clarity + 1;
				$clarity_sum = $clarity_sum + $curr['value'];
			}
		}
		
		if ($curr['metric_type'] == "pacing")
		{
			if(!in_array($curr['sunet_id'], $students_pacing))
			{
				$students_pacing[] = $curr['sunet_id'];
				$num_pacing = $num_pacing + 1;
				$pacing_sum = $pacing_sum + $curr['value'];		
			}	
		}
		
		$result->next();	
	}	
	
	$clarity = 0;
	if ($num_clarity != 0)
		$clarity = $clarity_sum / $num_clarity;
		
	$pacing = 0;
	if ($num_pacing != 0)
		$pacing = $pacing_sum / $num_pacing;

	$metrics = array(
			  "uniqueCourseNumber"=>$_GET['uniqueCourseNumber'],
			  "clarity"=>$clarity,
			  "pacing"=>$pacing
	);		
		
	print json_encode($metrics);
}

if ($_GET['action'] == "submit_metric")
{
	$time = sqlite_escape_string(date("D M j G:i:s T Y"));
	$result = $db->query("Insert INTO Metrics (sunet_id, class_id, metric_type, value, time) VALUES ('" . $_ENV["WEBAUTH_USER"] . "', " . $_GET['uniqueCourseNumber'] . ", '" . $_GET['metricName'] . "', " . $_GET['metricValue'] . ", '" . $time . "')");

	if ($result == false)
		$result = "false";
	else
		$result = "true";
		
	$success = array("success"=> $result);
	print json_encode($success);
}

?>